﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ASTClass;

namespace Visitor
{
    class MakeDotFile : IVisitor
    {

        FileStream file;
        StreamWriter sw = null;

        public MakeDotFile()
        {

        }

        public bool Initialize(string filename, string title)
        {

            try
            {
                file = new FileStream(filename, FileMode.Create, FileAccess.Write);
            }
            catch
            {
                return false;
            }
            sw = new StreamWriter(file);

            sw.WriteLine("digraph G {");
            sw.WriteLine("Title [label=\"" + title + "\",shape=box]");

            return true;

        }

        public void Visit(AST ast)
        {
            sw.Write(ast.UniqueName + "[label = \"" + ast.Name);
            if (ast.Operators.Count > 0)
            {
                sw.Write(" |");
                foreach (Operator i in ast.Operators)
                    sw.Write(i.ToString() + " ");
                sw.Write("|");
            }
            sw.Write("\"]\n");
            foreach (AST child in ast.Children)
            {
                sw.WriteLine(ast.UniqueName + " -> " + child.UniqueName);
                child.Accept(this);
            }
        }

    }
}
